using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 更新入库单处理器
    /// </summary>
    public class UpdateStockInOrderHandler : IRequestHandler<UpdateStockInOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<StockInOrder> _stockInOrderRepository;
        private readonly IMapper _mapper;

        public UpdateStockInOrderHandler(IBaseRespository<StockInOrder> stockInOrderRepository, IMapper mapper)
        {
            _stockInOrderRepository = stockInOrderRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理更新入库单请求
        /// </summary>
        /// <param name="request">更新入库单命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(UpdateStockInOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取入库单信息
                var stockInOrder = await _stockInOrderRepository.GetModelAsync(request.Id);
                if (stockInOrder == null || stockInOrder.Isdel)
                {
                    return new ApiResult<int>
                    {
                        Msg = "入库单不存在",
                        Code = ApiEnum.Failed
                    };
                }

                // 更新入库单信息
                _mapper.Map(request, stockInOrder);

                // 保存修改
                await _stockInOrderRepository.Update(stockInOrder);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "修改成功",
                    Data = stockInOrder.Id
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"修改失败，{ex.Message}",
                };
            }
        }
    }
}